package controller.ur;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import controller.CUtil;

import model.dao.AlbumDaoLocal;
import model.dao.PhotoDaoLocal;
import model.dao.UserDaoLocal;
import model.entity.Album;
import model.entity.Photo;
import model.entity.User;

/**
 * Servlet implementation class SPhotoAddFavorite
 */
public class SPhotoAddFavorite extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@EJB
	private PhotoDaoLocal photoDao;
	
	@EJB
	private AlbumDaoLocal albumDao;
	
	private Logger log=Logger.getLogger(SPhotoAddFavorite.class);
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SPhotoAddFavorite() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(!CUtil.checkLogIn(request, response))
			return;
		
		User user=(User)request.getSession().getAttribute("user");
		Integer photoId=Integer.parseInt((String)request.getParameter("photoId"));
		Photo photo=photoDao.findById(photoId);
		
		Album favorite=user.getFavorite();
		favorite.getPhotos().add(photo);
		photo.getAlbums().add(favorite);
		photoDao.merge(photo);
		albumDao.merge(favorite);
		
		log.info("Photo "+photo.toString() +" added to favorites by user "+user.toString());
		
		CUtil.redirecter(request, response, "SViewPhoto?photoId="+photoId);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
